<template>
  <div>
    <input ref="vedio-upload-input" class="vedio-upload-input" type="file" accept=".mp4" @change="handleClick">
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      拖曳文件到此,或者
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        {{ fileName ? fileName : '点击浏览' }}
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function// eslint-disable-line
  },
  data() {
    return {
      loading: false,
      fileName: ''
    }
  },
  methods: {
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('同时只支持一个文件!')
        return
      }
      const rawFile = files[0] // only use files[0]

      if (!this.isVedio(rawFile)) {
        this.$message.error('只支持上传 .mp4文件')
        return false
      }
      this.upload(rawFile)
      // e.stopPropagation()
      // e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['vedio-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['vedio-upload-input'].value = null // fix can't select the same excel
      this?.beforeUpload?.(rawFile)
      this.fileName = rawFile.name
      this?.onSuccess?.(rawFile)
    },
    isVedio(file) {
      return /\.(mp4)$/.test(file.name)
    }
  }
}
</script>

<style scoped>
.vedio-upload-input{
  display: none;
  z-index: -9999;
}
.drop{
  border: 2px dashed #bbb;
  width: 400px;
  max-width: 100%;
  height: 160px;
  line-height: 160px;
  font-size: 20px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>
